package cn.glc.daily.life.web.factory.login.core;

import cn.glc.daily.life.common.enums.CaptchaEnum;
import cn.glc.daily.life.common.exceptions.GlobalException;
import cn.glc.daily.life.infrastructure.po.UserAuthsPo;
import cn.glc.daily.life.infrastructure.repository.mysql.MysqlRepositories;
import cn.glc.daily.life.model.dto.LoginDto;
import cn.simon.free.redis.component.RedisSupport;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.Optional;

import static cn.glc.daily.life.common.enums.GlobalCodeEnum.CaptchaBusinessExceptionEnum.CAPTCHA_ERROR;

/**
 * 邮箱验证码登录(变相只用于测试短信验证码,因为,系统中账号可能不存在,但是发了邮件)
 *
 * @author simon
 * @date 2020/11/18 9:58
 * @copyright:
 * @modifier
 * @motto a no talent, people who have to study hard
 */
@Component("emailCodeLogin")
public class EmailCodeLogin extends DefaultLoginFactory {

    @Override
    public Long login(LoginDto loginDto) {
        String code = loginDto.getCredential();
        String key = CaptchaEnum.EMAIL_CAPTCHA.getPrefix().concat(loginDto.getIdentify());
        Object captcha = RedisSupport.jedisStringSupport.get(key);
        Optional.ofNullable(captcha).orElseThrow(() -> new GlobalException(CAPTCHA_ERROR));
        UserAuthsPo userAuthsPo = MysqlRepositories.userAuthsRepository.findByIdentifyAndType(loginDto.getIdentify(), loginDto.getType().getName());
        if (Objects.nonNull(userAuthsPo) && StringUtils.equals(code, (CharSequence) captcha)) {
            //登录成功后,修改这次的密码,用于签名校验时的salt参数
            userAuthsPo.setCredential(code);
            MysqlRepositories.userAuthsRepository.updateById(userAuthsPo);
            return userAuthsPo.getUid();
        }
        return null;
    }

    @Override
    public Boolean match(LoginDto loginDto) {
        return false;
    }
}
